package com.gxa.jjty.cjr.service.impl;

import com.gxa.jjty.cjr.mapper.AppServeMapper;
import com.gxa.jjty.cjr.mapper.ArticleMapper;
import com.gxa.jjty.cjr.pojo.Article;
import com.gxa.jjty.cjr.service.SearchService;
import com.gxa.jjty.core.common.JsonResult;
import com.gxa.jjty.core.pojo.AppServe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : 宸濯
 * Date: 2021/12/13 11:09
 * Description:
 * Version: V1.0
 */
@Service("searchService")
public class SearchServiceImpl implements SearchService {

    @Autowired(required = false)
    AppServeMapper appServeMapper;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Autowired
    ArticleMapper articleMapper;
    private static final String HOT_SEARCH="hotSearch";
    private static final String SEARCH_HISTORY="searchHistory:";

    @Override
    public Map<String, Object> findByName(Long id,String name) {
        //增加热门搜索的score值
        redisTemplate.opsForZSet().incrementScore(HOT_SEARCH, name, 1);
        //存历史记录
        redisTemplate.opsForList().remove(SEARCH_HISTORY+id, 1, name);
        redisTemplate.opsForList().leftPush(SEARCH_HISTORY+id,name);
//        redisTemplate.opsForSet().add(SEARCH_HISTORY+id,name);

        final JsonResult jsonResult = new JsonResult();
        List<AppServe> appServiceList = appServeMapper.findByName(name);
        Example example = new Example(Article.class);
        example.createCriteria().orLike("title",name).orLike("content",name);
        List<Article> articles = articleMapper.selectByExample(example);
        Map<String,Object> map= new  HashMap<>(16);
        map.put("appServiceList",appServiceList);
        map.put("articleList",articles);
        jsonResult.setCode("1");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }

    @Override
    public Map<String, Object> searchRecode(Long id){
//        Set<Object> searchHistory = redisTemplate.opsForSet().members(SEARCH_HISTORY + id);
        List<Object> searchHistory = redisTemplate.opsForList().range(SEARCH_HISTORY + id, 0, -1);
        Set<ZSetOperations.TypedTuple<Object>> hotSearch = redisTemplate.opsForZSet().reverseRangeWithScores(HOT_SEARCH, 0, 2);
        Map<String,Object> map=new HashMap<>(16);
        map.put(SEARCH_HISTORY.substring(0,SEARCH_HISTORY.length()-1),searchHistory);
        map.put(HOT_SEARCH,hotSearch);
        final JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }
}
